local skynet = require "skynet"
local filelog = require "filelog"
local msghelper = require "agenthelper"
local timetool = require "timetool"
local marquee = require "marquee"
local msgproxy = require "msgproxy"
local configdao = require "configdao"
require "enum"

local  Heart = {}

--[[
//心跳包请求
message HeartReq {
	optional Version version = 1;	
}
//心跳包响应
message HeartRes {
	optional int32 errcode = 1; //错误原因 0表示成功
	optional string errcodedes = 2; //错误描述
}
]]

local last_querymarquee_time = 0

function  Heart.process(session, source, fd, request)
	local responsemsg = {
		errcode = EErrCode.ERR_SUCCESS,
	}
	local server = msghelper:get_server()

	--检查当前登陆状态
	if not msghelper:is_login_success() then
		filelog.sys_warning("Heart.process invalid server state", server.state)
		responsemsg.errcode = EErrCode.ERR_INVALID_REQUEST
		responsemsg.errcodedes = "无效的请求!"
		msghelper:send_resmsgto_client(fd, "HeartRes", responsemsg)		
		return
	end

	server.last_heart_time = timetool.get_time()
	if server.is_player_leave then
		if server.roomsvr_id ~= nil and server.roomsvr_id ~= "" then
			msgproxy.sendrpc_reqmsgto_roomsvrd(server.gameid, nil, server.roomsvr_id, server.roomsvr_table_address, "playerleave", {rid=server.rid, is_leave=false})
		end
		server.is_player_leave = false
	end
	responsemsg.servertime = timetool.get_time()

	msghelper:send_resmsgto_client(fd, "HeartRes", responsemsg)

	--检查是否下发跑马灯
	local now_time = timetool.get_time()
	if server.marquee_index ~= nil and last_querymarquee_time + configdao.get_common_conf("marquee_space_time") < now_time then
		last_querymarquee_time = now_time
		local index, noticemsg = marquee.querymsg(server.marquee_index)
		if index ~= server.marquee_index then
			server.marquee_index = index
			msghelper:send_noticemsgto_client(fd, "MarqueemsgNtc", noticemsg)			
		end
	end		
end

return Heart